package com.ly.algorithm.offerpointer;

import java.util.*;

/**
 * @Classname Offer32I
 * @Description
 *
 * 从上到下打印出二叉树的每个节点，同一层的节点按照从左到右的顺序打印。
 *
 *  
 *
 * 例如:
 * 给定二叉树: [3,9,20,null,null,15,7],
 *
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * 返回：
 *
 * [3,9,20,15,7]
 *
 *
 * @Date 2021/1/29 14:12
 * @Author 冷心影翼
 */
public class Offer32I {

    public static void main(String[] args) {
        Solution32I solution32I = new Solution32I();
        int[] ints = solution32I.levelOrder(TreeNode.init(new int[]{3, 9, 20,-1,-1, 15, 7}));
        System.out.println(Arrays.toString(ints));
    }

}


class Solution32I {

    public int[] levelOrder(TreeNode root) {
        if(root == null) {
            return new int[0];
        }
        List<Integer> list = new ArrayList<>();
        ArrayDeque<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode pop = queue.poll();
            list.add(pop.val);
            if(pop.left != null) {
                queue.add(pop.left);
            }
            if(pop.right != null) {
                queue.add(pop.right);
            }
        }
        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;
    }
}